package edu.mse.camel.client.uml.collab.loginstate;

import org.eclipse.swt.graphics.RGB;

import edu.mse.camel.client.eventbus.pubsub.EventManager;
import edu.mse.camel.client.eventbus.pubsub.ISubscriber;
import edu.mse.camel.client.events.IEvent;
import edu.mse.camel.client.events.server.NotifySessionParticipantChange;
import edu.mse.camel.client.events.server.QueryLoginStatus;
import edu.mse.camel.client.session.team.QuerySessionParticipantStatus;
import edu.mse.camel.client.uml.collab.handlers.GenericReceiveEventHandler;

public class SessionState implements ISubscriber {

	public SessionState() {
		updateStatus();
	}
	
	/**
	 * If the value of this is null, then that means I am not 
	 * logged in and if it does have a value then thats the id of the
	 * user that has logged in
	 */
	public static String myUserID = null;
	
	/**
	 * This is used to check if I am in a session or not
	 */
	public static boolean inSession = false;
	
	public static RGB myRGB = null;
	
	public static boolean isFacilitator = false;
	
	public static volatile boolean targetViewAvailable = false;
	public static GenericReceiveEventHandler handler;
	
	@Override
	public void notifyEvent(IEvent e) {
		if (e instanceof NotifySessionParticipantChange) {
			updateStatus();
		}
		
	}

	private void updateStatus() {
		QueryLoginStatus qls = new QueryLoginStatus();
		EventManager.getInstance().dispatchEventSynchronous(qls, true);
		if (qls.isOpSuccessful()) {
			if (qls.isLoggedIn()) {
				SessionState.myUserID = qls.getUserId();
			}
		} else {
			SessionState.myUserID = null;
			return;
		}
		
		QuerySessionParticipantStatus qspEvent = new QuerySessionParticipantStatus();
		EventManager.getInstance().dispatchEventSynchronous(qspEvent, true);
		
		if (qspEvent.isOpSuccessful()) {
			for(QuerySessionParticipantStatus.ParticipantInternal 
					status : qspEvent.getParticipants()) {
				if(status.isFacilitator()) {
					if(SessionState.myUserID.equalsIgnoreCase(status.getId())) {
						SessionState.isFacilitator = true;
						break;
					}
				}
			}
		}
	}
	
}
